﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.Configuration;


namespace KD.Sms.PlateRecognition
{
    public partial class frmLpr : Form
    {
        public frmLpr()
        {
            InitializeComponent();
        }

        #region 视频抓拍用到的一些变量
        public delegate void UpdatePlateInfo(string strIP, string strNum, string strColor, uint nVehicleColor,
            uint nAlarmType, short nVehiclType, uint nCapTime, int index, string strLogName, ICE_RECT_S stVlprInfo);
        public UpdatePlateInfo updatePlateInfo;
        public delegate void UpdateStatus(int index, int type);
        public UpdateStatus updateStatus;
        public delegate void UpdateTriggerStatus(int index, uint nStatus);
        public UpdateTriggerStatus triggerStatus;
        public delegate void UpdatePortInfo(string strIp, uint len, int index, string data, int type);
        public UpdatePortInfo updatePortInfo;
        public delegate void UpdateDeviceEvent(string strIP, uint nType, uint ndata1, uint ndata2, uint ndata3, uint ndata4, int nFlag, int road);
        public UpdateDeviceEvent updateDeviceEvent;

        private bool bTalk = false;
        private UInt32 nCurrentStatus = 0;
        private UInt32 nStatus = 0;
        private StringBuilder strMac = new StringBuilder();
        private UInt32 nGate2Num = 0;
        private bool bRecord = false;
        private bool bPreview = true;
        private bool bClose = false;
        private IntPtr pUid = IntPtr.Zero;
        private uint nDeviceEventCount = 0;

        public ICE_VBR_RESULT_S vbrResult = new ICE_VBR_RESULT_S();
        public ICE_VDC_PICTRUE_INFO_S vdcInfo = new ICE_VDC_PICTRUE_INFO_S();
        public ICE_VLPR_OUTPUT_S vlprInfo = new ICE_VLPR_OUTPUT_S();

        Mutex mutex = new Mutex();
        Mutex mutexThread = new Mutex();
        public static Thread[] mythread = new Thread[4] { null, null, null, null };
        public static Thread threadTrigger = null;
        public static Thread threadOpenGate = null;
        public static Thread threadStatus = null;
        public static Thread threadOpenGate2 = null;
        public static Thread[] threadBroadcast = new Thread[4] { null, null, null, null };

        //设置变量
        private string EC_SaveCaptureDir = "D:\\";
        private bool EC_IsConnect { set; get; }
        private string EC_LprIp = "192.168.2.15";
        private string EC_LprPassword = "123456";
        private bool EC_SaveImageAll { set; get; }
        private bool EC_SaveImageCarNo { set; get; }
        private bool EC_UsePasswordLogin { set; get; }

        private ipcsdk.ICE_IPCSDK_OnPlate onPlate;
        private ipcsdk.ICE_IPCSDK_OnFrame_Planar onFrame;
        private ipcsdk.ICE_IPCSDK_OnDeviceEvent onDeviceEvent;
        private ipcsdk.ICE_IPCSDK_OnIOEvent onIOEvent;


        bool _bShowBoxInfo = false;
        bool _bShowOther = false;

        #endregion


        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmLpr_Load(object sender, EventArgs e)
        {
            ActionCenter.Action.Instance.CaptureHead += OnCaptureHead;
            ActionCenter.Action.Instance.CaptureCarNo += OnCaptureCarNo;
            EC_IsConnect = false;
            EC_SaveImageAll = false;
            EC_SaveImageCarNo = false;

            //读取配置文件参数
            DoInitConfig();

            if (!NetJudger.DoJudge(EC_LprIp))
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "车牌识别摄像头无法连接");
                return;
            }

            ipcsdk.ICE_IPCSDK_Init(); //调用全局初始化

            onFrame = new ipcsdk.ICE_IPCSDK_OnFrame_Planar(SDK_OnFrame);
            onPlate = new ipcsdk.ICE_IPCSDK_OnPlate(SDK_OnPlate);
            onDeviceEvent = new ipcsdk.ICE_IPCSDK_OnDeviceEvent(SDK_OnDeviceEvent);
            onIOEvent = new ipcsdk.ICE_IPCSDK_OnIOEvent(SDK_OnIOEvent);

            strMac = new StringBuilder(64);

            updatePlateInfo = new UpdatePlateInfo(showCount);
            updateStatus = new UpdateStatus(showStatus);
            triggerStatus = new UpdateTriggerStatus(showTriggerStatus);
            updateDeviceEvent = new UpdateDeviceEvent(showDeviceEvent);
            //为语音播放序号下拉框赋值0-145
            for (int pos = 0; pos < 146; pos++)
            {
                comboBox_BIndex1.Items.Add(pos.ToString());
            }
            comboBox_BIndex1.SelectedIndex = 0;

            ipcsdk.ICE_IPCSDK_SetDeviceEventCallBack(IntPtr.Zero, onDeviceEvent, new IntPtr(0));

            if (threadStatus != null)
            {
                threadStatus.Abort();
                threadStatus = null;
            }
            //threadStatus = new Thread(new ThreadStart(getStatus));//开启获取相机状态线程
            //threadStatus.Start();

            panDebugInfo.Visible = false;
            panDebugControl.Visible = false;

            _bShowBoxInfo = panDebugInfo.Visible == true;
            _bShowOther = panDebugControl.Visible == true;

            DoConnect();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmLpr_FormClosing(object sender, FormClosingEventArgs e)
        {
            DoDisconnect();
            if (threadStatus != null)
            {
                threadStatus.Abort();
                threadStatus = null;
            }
        }

        /// <summary>
        /// 手动触发
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnCaptureCarNo(object send, ActionCenter.CommonEventArgs e)
        {
            DoCatchHandle();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnCaptureHead(object send, ActionCenter.CommonEventArgs e)
        {
            if (pUid != IntPtr.Zero)
            {
                uint pLen = 0;
                byte[] pdata = new byte[1048576];
                UInt32 success = ipcsdk.ICE_IPCSDK_Capture(pUid, pdata, 1048576, ref pLen);//获取一张抓拍图
                if (1 == success && pLen > 0)
                {
                    if (pLen > 0)
                    {
                        byte[] datajpg2 = new byte[pLen];
                        Array.Copy(pdata, 0, datajpg2, 0, datajpg2.Length);//拷贝数据
                        CacheMemoryCenter.E_CaptureHead = ImageHelper.ZoomImage(ImageHelper.CropImage(ImageHelper.ByteToImage(datajpg2), new Rectangle(170, 150, 1280, 800)), 338, 546);
                        datajpg2 = null;
                    }
                }
                pdata = null;
            }
            else
                CacheMemoryCenter.E_CaptureHead = null;
        }

        //将收到的实时识别数据和断网识别数据显示在界面上
        public void showCount(string strIP, string strNum, string strColor, uint nVehicleColor,
            uint nAlarmType, short nVehiclType, uint nCapTime, int index, string strLogName, ICE_RECT_S stRect)
        {
             
            if (listBoxInfo.Items.Count > 50)
            {
                listBoxInfo.Items.Clear();
            }
            if (pUid != IntPtr.Zero)
            {
                if (nCapTime == 0)//实时数据
                {
                    if (!string.IsNullOrEmpty(strNum))
                    {
                        if (_bShowOther)
                            labelPlate.Text = strNum;
                        if (_bShowBoxInfo)
                            listBoxInfo.Items.Insert(0, strNum + " " + strColor);//将实时数据显示在界面上（右边的显示框）
                        //进行车号识别处理
                        ActionCenter.Action.Instance.DoSetCarNum(DiscriminateType.LprCapture, strNum, false);
                    }
                }
            }
        }

        /// <summary>
        /// 抓图保存
        /// </summary>
        /// <param name="picData"></param>
        /// <param name="strIP"></param>
        /// <param name="strNumber"></param>
        /// <param name="bIsPlate"></param>
        /// <param name="nCapTime"></param>
        /// <param name="fResFuture"></param>
        /// <param name="strLogName"></param>
        public void SavePic(byte[] picData, string strIP, string strNumber, bool bIsPlate, UInt32 nCapTime, float[] fResFuture, string strLogName)
        {
            DateTime dt = new DateTime();
            if (nCapTime == 0)
            {
                dt = DateTime.Now;
            }
            else
            {
                dt = DateTime.Parse("1970-01-01 08:00:00").AddSeconds(nCapTime);
            }

            string strDir = EC_SaveCaptureDir + @"抓拍\" + dt.ToString("yyyyMMdd");
            if (!Directory.Exists(strDir))
            {
                Directory.CreateDirectory(strDir);
            }

            string strPicName;
            if (strLogName.Length != 0)
                strPicName = strDir + @"\" + dt.ToString("yyyyMMddHHmmss") + "_" + strLogName + "_" + strNumber;
            else
                strPicName = strDir + @"\" + dt.ToString("yyyyMMddHHmmss") + "_" + strNumber;
            if (bIsPlate)//车牌图，图片名后缀加_plate
                strPicName += "_plate";
            strPicName += ".jpg";
            if (File.Exists(strPicName))//如果图片名存在，则在文件名末尾加数字以分辨，如XXX_1.jpg;XXX_2.jpg
            {
                int count = 1;
                while (count <= 10)
                {
                    strPicName = strDir + @"\" + dt.ToString("yyyyMMddHHmmss") + "_" + strNumber;
                    if (bIsPlate)
                    {
                        strPicName += "_plate";
                    }
                    strPicName += "_" + count.ToString() + ".jpg";

                    if (!File.Exists(strPicName))
                    {
                        break;
                    }
                    count++;
                }
            }
            //存图
            try
            {
                FileStream fs = new FileStream(strPicName, FileMode.Create, FileAccess.Write);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(picData);
                bw.Close();
                fs.Close();
            }
            catch (System.Exception ex)
            {

            }

            //保存特征码
            if (bIsPlate || null == fResFuture)
                return;

            string strFileName = strDir + @"\" + "vbr_record.txt";

            string strContent = "";
            //将车辆特征码存到字符串中
            for (int i = 0; i < 20; i++)
            {
                if (i != 0)
                    strContent += " ";
                strContent += fResFuture[i].ToString("0.000000");
            }
            //将车辆特征码数据追加到文件中
            try
            {
                StreamWriter sw = new StreamWriter(strFileName, true, Encoding.Unicode);
                if (null != sw)
                {
                    strContent = dt.ToString("yyyyMMddHHmmss") + "_" + strLogName + "_" + strNumber + ".jpg" + " " + strNumber + " " + strContent + "\r\n";
                    sw.Write(strContent);
                    sw.Close();
                }
            }
            catch (System.Exception ex)
            {

            }

        }

        private bool m_bExit = false;

        public void on_plate(string bstrIP, string bstrNumber, string bstrColor, IntPtr vPicData, UInt32 nPicLen,
          IntPtr vCloseUpPicData, UInt32 nCloseUpPicLen, short nSpeed, short nVehicleType, short nReserved1, short nReserved2, Single fPlateConfidence,
          UInt32 nVehicleColor, UInt32 nPlateType, UInt32 nVehicleDir, UInt32 nAlarmType, UInt32 nCapTime, Int32 index, uint u32ResultHigh, uint u32ResultLow)
        {
            if (m_bExit)
                return;
#if VERSION32
            IntPtr vdcPtr = (IntPtr)u32ResultLow;
#else
            ulong tmp = ((ulong)u32ResultHigh << 32) + (ulong)u32ResultLow;
            IntPtr vdcPtr = (IntPtr)tmp;
#endif
            if (vdcPtr != IntPtr.Zero)
            {
                //将数据拷贝到ICE_VDC_PICTRUE_INFO_S结构体
                vdcInfo = (ICE_VDC_PICTRUE_INFO_S)Marshal.PtrToStructure(vdcPtr, typeof(ICE_VDC_PICTRUE_INFO_S));

                //获得车款结构体指针，并拷贝
                if (vdcInfo.pstVbrResult != IntPtr.Zero)
                {
                    vbrResult = (ICE_VBR_RESULT_S)Marshal.PtrToStructure(vdcInfo.pstVbrResult, typeof(ICE_VBR_RESULT_S));
                    if (vbrResult.szLogName.Length == 0)
                        vbrResult.szLogName = "未知";
                    //委托，用于显示识别数据(showCount),vdcInfo.stPlateInfo表示车牌信息
                    this.BeginInvoke(updatePlateInfo, bstrIP, bstrNumber, bstrColor,
                        nVehicleColor, nAlarmType, nVehicleType, nCapTime, index, vbrResult.szLogName, vdcInfo.stPlateInfo.stPlateRect);
                }
                else
                    this.BeginInvoke(updatePlateInfo, bstrIP, bstrNumber, bstrColor,
                        nVehicleColor, nAlarmType, nVehicleType, nCapTime, index, "", vdcInfo.stPlateInfo.stPlateRect);//委托，用于显示识别数据(showCount),vdcInfo.stPlateInfo表示车牌信息
            }
            else
                this.BeginInvoke(updatePlateInfo, bstrIP, bstrNumber, bstrColor,
                    nVehicleColor, nAlarmType, nVehicleType, nCapTime, index, "", null);//委托，用于显示识别数据(showCount)

            if (EC_SaveImageAll && nPicLen > 0)//全景图数据长度不为0
            {
                IntPtr ptr2 = (IntPtr)vPicData;
                byte[] datajpg2 = new byte[nPicLen];
                Marshal.Copy(ptr2, datajpg2, 0, datajpg2.Length);//拷贝图片数据
                //存图
                if (vdcInfo.pstVbrResult != IntPtr.Zero)
                    SavePic(datajpg2, bstrIP, bstrNumber, false, nCapTime, vbrResult.fResFeature, vbrResult.szLogName);
                else
                    SavePic(datajpg2, bstrIP, bstrNumber, false, nCapTime, null, "");
                EC_SaveImageAll = false;
            }


            if (EC_SaveImageCarNo && nCloseUpPicLen > 0)//车牌图数据长度不为0
            {
                IntPtr ptr = (IntPtr)vCloseUpPicData;
                byte[] datajpg = new byte[nCloseUpPicLen];
                Marshal.Copy(ptr, datajpg, 0, datajpg.Length);//拷贝图片数据
                //存图
                if (vdcInfo.pstVbrResult != IntPtr.Zero)
                    SavePic(datajpg, bstrIP, bstrNumber, true, nCapTime, null, vbrResult.szLogName);
                else
                    SavePic(datajpg, bstrIP, bstrNumber, true, nCapTime, null, "");
                EC_SaveImageCarNo = false;
            }
        }

        /// <summary>
        /// 实时抓拍
        /// </summary>
        /// <param name="pvParam"></param>
        /// <param name="pcIP"></param>
        /// <param name="pcNumber"></param>
        /// <param name="pcColor"></param>
        /// <param name="pcPicData"></param>
        /// <param name="u32PicLen"></param>
        /// <param name="pcCloseUpPicData"></param>
        /// <param name="u32CloseUpPicLen"></param>
        /// <param name="nSpeed"></param>
        /// <param name="nVehicleType"></param>
        /// <param name="nReserved1"></param>
        /// <param name="nReserved2"></param>
        /// <param name="fPlateConfidence"></param>
        /// <param name="u32VehicleColor"></param>
        /// <param name="u32PlateType"></param>
        /// <param name="u32VehicleDir"></param>
        /// <param name="u32AlarmType"></param>
        /// <param name="u32SerialNum"></param>
        /// <param name="uCapTime"></param>
        /// <param name="u32ResultHigh"></param>
        /// <param name="u32ResultLow"></param>
        public void SDK_OnPlate(System.IntPtr pvParam,
                    [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
                    [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcNumber,
                    [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcColor,
                    System.IntPtr pcPicData, uint u32PicLen, System.IntPtr pcCloseUpPicData, uint u32CloseUpPicLen,
                    short nSpeed, short nVehicleType, short nReserved1, short nReserved2,
                    float fPlateConfidence, uint u32VehicleColor, uint u32PlateType, uint u32VehicleDir, uint u32AlarmType,
                    uint u32SerialNum, uint uCapTime, uint u32ResultHigh, uint u32ResultLow)
        {
            int index = (int)pvParam;
            if (m_bExit || bClose)
                return;
            on_plate(pcIP, pcNumber, pcColor, pcPicData, u32PicLen, pcCloseUpPicData, u32CloseUpPicLen,
                nSpeed, nVehicleType, nReserved1, nReserved2, fPlateConfidence,
                u32VehicleColor, u32PlateType, u32VehicleDir, u32AlarmType, 0, index, u32ResultHigh, u32ResultLow);
        }


        private int[] frame_count = new int[4] { 0, 0, 0, 0 };

        /// <summary>
        /// 
        /// </summary>
        /// <param name="u32Timestamp"></param>
        /// <param name="pu8DataY"></param>
        /// <param name="pu8DataU"></param>
        /// <param name="pu8DataV"></param>
        /// <param name="s32LinesizeY"></param>
        /// <param name="s32LinesizeU"></param>
        /// <param name="s32LinesizeV"></param>
        /// <param name="s32Width"></param>
        /// <param name="s32Height"></param>
        /// <param name="i"></param>
        public void on_frame(UInt32 u32Timestamp, IntPtr pu8DataY, IntPtr pu8DataU, IntPtr pu8DataV, Int32 s32LinesizeY, Int32 s32LinesizeU, Int32 s32LinesizeV, Int32 s32Width, Int32 s32Height, Int32 i)
        {
            if (m_bExit)
                return;

            mutex.WaitOne();
            string strDir = EC_SaveCaptureDir + @"抓拍全景\" + EC_LprIp + @"\" + DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(strDir))
            {
                Directory.CreateDirectory(strDir);
            }

            string strPicName = strDir + @"\" + "test.bmp";

            if (0 == (frame_count[i] % 30))
            {

                try
                {
                    //拷贝数据
                    byte[] datay = new byte[s32Width * s32Height];
                    for (int j = 0; j < s32Height; j++)
                        Marshal.Copy((IntPtr)pu8DataY + j * s32LinesizeY, datay, j * s32Width, s32Width);

                    byte[] datau = new byte[s32Width * s32Height / 4];
                    for (int j = 0; j < s32Height / 2; j++)
                        Marshal.Copy((IntPtr)pu8DataU + j * s32LinesizeU, datau, j * s32Width / 2, s32Width / 2);

                    byte[] datav = new byte[s32Width * s32Height / 4];
                    for (int j = 0; j < s32Height / 2; j++)
                        Marshal.Copy((IntPtr)pu8DataV + j * s32LinesizeV, datav, j * s32Width / 2, s32Width / 2);

                    byte[] rgb24 = new byte[s32Width * s32Height * 3];

                    util.Convert(s32Width, s32Height, datay, datau, datav, ref rgb24);
                    //存图
                    FileStream fs = new FileStream(strPicName, FileMode.Create, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);

                    bw.Write('B');
                    bw.Write('M');
                    bw.Write(rgb24.Length + 54);
                    bw.Write(0);
                    bw.Write(54);
                    bw.Write(40);
                    bw.Write(s32Width);
                    bw.Write(s32Height);
                    bw.Write((ushort)1);
                    bw.Write((ushort)24);
                    bw.Write(0);
                    bw.Write(rgb24.Length);
                    bw.Write(0);
                    bw.Write(0);
                    bw.Write(0);
                    bw.Write(0);

                    bw.Write(rgb24, 0, rgb24.Length);
                    bw.Close();
                    fs.Close();

                }
                catch (System.Exception ex)
                {
                    //MessageBox.Show("frame" + ex.Message);
                }

                frame_count[i] = 0;
            }
            frame_count[i]++;
            mutex.ReleaseMutex();
        }


        public void SDK_OnFrame(System.IntPtr pvParam, uint u32Timestamp, System.IntPtr pu8DataY,
            System.IntPtr pu8DataU, System.IntPtr pu8DataV, int s32LinesizeY, int s32LinesizeU,
            int s32LinesizeV, int s32Width, int s32Height)
        {
            int index = (int)pvParam;
            if (m_bExit || bClose)
                return;
            on_frame(u32Timestamp, pu8DataY, pu8DataU, pu8DataV, s32LinesizeY,
                s32LinesizeU, s32LinesizeV, s32Width, s32Height, index);
        }


        public void showDeviceEvent(string strIP, uint nType, uint ndata1, uint ndata2, uint ndata3, uint ndata4, int nFlag, int road)
        {
            if (listBoxInfo.Items.Count > 1024)
            {
                listBoxInfo.Items.Clear();
            }
            string strText = "";
            if (0 == nFlag)
            {
                if (0 == nType)
                {
                    strText = "第" + (road + 1).ToString() + "路 " + strIP + " IO状态改变： " +
                        ndata1.ToString() + ndata2.ToString() + ndata3.ToString() + ndata4.ToString();
                }
                if (_bShowBoxInfo)
                    listBoxInfo.Items.Insert(0, strText);
                return;
            }
            else
            {
                if (0 == nType)
                    strText = strIP + ":当前状态离线";
                else if (1 == nType)
                    strText = strIP + ":当前状态在线";
                else if (2 == nType)
                {
                    nDeviceEventCount++;
                    strText = nDeviceEventCount.ToString() + " " + strIP + " IO状态改变： " +
                        ndata1.ToString() + ndata2.ToString() + ndata3.ToString() + ndata4.ToString();
                }
            }

            if (_bShowBoxInfo)
                listBoxInfo.Items.Insert(0, strText);
        }

        public void SDK_OnDeviceEvent(System.IntPtr pvParam,
           [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
           uint u32EventType, uint u32EventData1, uint u32EventData2, uint u32EventData3, uint u32EventData4)
        {
            IAsyncResult syncResult = this.BeginInvoke(updateDeviceEvent, pcIP, u32EventType, u32EventData1,
                u32EventData2, u32EventData3, u32EventData4, 1, 0);
        }

        public void SDK_OnIOEvent(System.IntPtr pvParam,
            [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
            uint u32EventType, uint u32IOData1, uint u32IOData2, uint u32IOData3, uint u32IOData4)
        {
            IAsyncResult syncResult = this.BeginInvoke(updateDeviceEvent, pcIP, u32EventType, u32IOData1,
                u32IOData2, u32IOData3, u32IOData4, 0, (int)pvParam);
        }

        /// <summary>
        /// 程序参数初始化
        /// </summary>
        private void DoInitConfig()
        {
            EC_LprIp = ConfigurationManager.AppSettings["CaptureIp"].ToString();
            EC_LprPassword = ConfigurationManager.AppSettings["CapturePassword"].ToString();
            EC_SaveImageAll = ConfigurationManager.AppSettings["SaveCapture"].ToString() == "1";
            EC_SaveImageCarNo = ConfigurationManager.AppSettings["SaveCaptureCarNo"].ToString() == "1";
            EC_SaveCaptureDir = ConfigurationManager.AppSettings["SaveCaptureCarNo"].ToString();
        }

        /// <summary>
        /// 显示相机连接状态， 打开道闸2成功，发送RS485、RS232数据成功
        /// </summary>
        /// <param name="index"></param>
        /// <param name="type"></param>
        public void showStatus(int index, int type)
        {
            switch (type)
            {
                case 0://连接状态
                    if (nStatus == 1)
                    {
                        labelStatus.Text = "在线 " + strMac[index];
                    }
                    else
                        labelStatus.Text = "离线 " + strMac[index];
                    break;
                case 1://打开道闸数
                    //textBoxGateNum[index].Text = nGateNum[index].ToString();
                    break;
                case 2://软触发数
                    //textBoxTriggerNum[index].Text = nTriggerNum[index].ToString();
                    break;
                case 3://打开道闸2数
                    nGate2Num++;
                    string strText = nGate2Num.ToString() + ": sdk" + (index + 1).ToString() + " 打开道闸2成功。";
                    if (_bShowBoxInfo)
                        listBoxInfo.Items.Insert(0, strText);
                    break;
            }
        }

        //显示软触发状态
        public void showTriggerStatus(int index, uint nStatus)
        {
            string strText = "相机" + (index + 1).ToString();
            switch (nStatus)
            {
                case 0:
                    strText += "：软触发失败";
                    break;
                case 2:
                    strText += ": 正在识别";
                    break;
                case 3:
                    strText += ": 算法未启动";
                    break;
            }

            if (strText == null)
                return;
            if (_bShowBoxInfo)
                listBoxInfo.Items.Insert(0, strText);
        }


        //获取连接状态线程
        private void getStatus()
        {
            while (true)
            {
                Thread.Sleep(1000);
                if (pUid != IntPtr.Zero || bClose)
                {
                    //mutexThread.WaitOne();
                    nCurrentStatus = ipcsdk.ICE_IPCSDK_GetStatus(pUid);//获取连接状态
                                                                       //mutexThread.ReleaseMutex();
                    if (nCurrentStatus != nStatus && pUid != IntPtr.Zero)
                    {
                        //mutexThread.WaitOne();
                        ipcsdk.ICE_IPCSDK_GetDevID(pUid, strMac);//获取相机mac地址
                                                                 //mutexThread.ReleaseMutex();
                        nStatus = nCurrentStatus;
                        IAsyncResult syncResult = this.BeginInvoke(updateStatus, 0, 0);//委托，显示连接信息
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            DoConnect();
        }

        private void DoConnect()
        {
            if (NetJudger.DoJudge(EC_LprIp))
            {
                EC_UsePasswordLogin = false;
                IntPtr videoHwnd = pictureBox1.Handle;
                if (videoHwnd != IntPtr.Zero)
                {
                    if (EC_UsePasswordLogin) //使用密码连接
                    {
                        pUid = ipcsdk.ICE_IPCSDK_OpenPreview_Passwd(EC_LprIp, EC_LprPassword, 1, 1,
                            (uint)videoHwnd, onPlate, new IntPtr(0)); //使用带密码的接口连接相机，并且设置车牌识别数据回调onPlate
                        if (pUid == IntPtr.Zero)
                        {
                            MessageBox.Show("相机1连接失败,密码错误或者网络不好！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        else
                            EC_IsConnect = true;
                    }
                    else
                    {
                        //使用不带密码的接口连接相机
                        pUid = ipcsdk.ICE_IPCSDK_OpenPreview(EC_LprIp, 1, 1, (uint)videoHwnd, onPlate, new IntPtr(0));
                        if (pUid == IntPtr.Zero)
                        {
                            MessageBox.Show("相机1连接失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        else
                            EC_IsConnect = true;
                    }
                }
                else
                {
                    MessageBox.Show("未获得视频播放窗口");
                    return;
                }

                ////设置断网续传回调
                //ipcsdk.ICE_IPCSDK_SetPastPlateCallBack(pUid, onPastPlate, new IntPtr(0));

                //IO变化事件
                ipcsdk.ICE_IPCSDK_SetIOEventCallBack(pUid, onIOEvent, new IntPtr(0));

                btnConnect.Enabled = false;
                buttonDisconnect.Enabled = true;
                button_broadcast.Enabled = true;
                bPreview = true;
                bClose = false;
            }
            else
                FormHelper.ApplicationShow(UI.MsgType.Error, "车牌识别摄像头网络中断");
        }



        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            DoDisconnect();
        }

        /// <summary>
        /// 断开链接
        /// </summary>
        private void DoDisconnect()
        {
            if (pUid == IntPtr.Zero)
                return;

            bClose = true;
            try
            {
                if (bTalk) //在进行对讲
                {
                    ipcsdk.ICE_IPCSDK_EndTalk(pUid);//结束对讲
                    bTalk = false;
                }

                if (bRecord) //在进行录像
                {
                    bRecord = false;
                    if (null != mythread[0])
                    {
                        mythread[0].Abort();
                        mythread[0] = null;
                    }
                    ipcsdk.ICE_IPCSDK_StopRecord(pUid); //结束录像
                }

                mutexThread.WaitOne();
                ipcsdk.ICE_IPCSDK_Close(pUid);//断开连接
                pUid = IntPtr.Zero;
                mutexThread.ReleaseMutex();
            }
            catch (System.Exception ex)
            {

            }

            if (bPreview)
            {
                bPreview = false;
            }

            labelStatus.Text = "离线";
            frame_count[0] = 0;
            nCurrentStatus = 0;
            nStatus = 0;
            btnConnect.Enabled = true;
            buttonDisconnect.Enabled = false;
            button_broadcast.Enabled = false;
        }


        /// <summary>
        /// 手动抓拍
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHandle_Click(object sender, EventArgs e)
        {
            DoCatchHandle();
        }

        /// <summary>
        /// 语音播报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_broadcast_Click(object sender, EventArgs e)
        {
            DoSendVoice((ushort)comboBox_BIndex1.SelectedIndex);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCapture_Click(object sender, EventArgs e)
        {
            DoCapture();
        }

        private void button_openGate1_Click(object sender, EventArgs e)
        {
            DoOpenGate1();
        }

        private void button_openGate2_Click(object sender, EventArgs e)
        {
            DoOpenGate2();
        }


        #region  本窗体使用及对外提供的一些方法


        /// <summary>
        /// 手动抓拍识别
        /// </summary>
        public void DoCatchHandle()
        {
            if (pUid != IntPtr.Zero)
            {
                StringBuilder strNum = new StringBuilder(32);
                StringBuilder strColor = new StringBuilder(64);
                uint len = 0;
                byte[] pdata = new byte[1048576];
                uint success = ipcsdk.ICE_IPCSDK_Trigger(pUid, strNum, strColor, pdata, 1048576, ref len);//软触发
                pdata = null;
                strNum = null;
                strColor = null;
            }
        }

        /// <summary>
        /// 截图
        /// </summary>
        public void DoCapture()
        {
            if (pUid != IntPtr.Zero)
            {
                uint pLen = 0;
                byte[] pdata = new byte[1048576];
                UInt32 success = ipcsdk.ICE_IPCSDK_Capture(pUid, pdata, 1048576, ref pLen);//获取一张抓拍图
                if (1 == success && pLen > 0)
                {
                    if (pLen > 0)
                    {
                        byte[] datajpg2 = new byte[pLen];
                        Array.Copy(pdata, 0, datajpg2, 0, datajpg2.Length);//拷贝数据
                        SavePic(ImageHelper.ImageToByte(ImageHelper.ZoomImage(ImageHelper.CropImage(ImageHelper.ByteToImage(datajpg2), new Rectangle(270, 100, 1280, 800)), 338, 546)), EC_LprIp, "", false, 0, null, "");//保存图片
                        datajpg2 = null;
                    }
                    string info = @"进行了只抓拍不识别的操作";
                    if (_bShowBoxInfo)
                        listBoxInfo.Items.Insert(0, info);//在右侧显示栏中显示
                }
                pdata = null;
            }
        }


        /// <summary>
        /// 语音播报
        /// </summary>
        /// <param name="value"></param>
        public void DoSendVoice(ushort value)
        {
            if (pUid == IntPtr.Zero)
                return;
            ipcsdk.ICE_IPCSDK_Broadcast(pUid, value);//语音播报
        }

        /// <summary>
        /// 打开道闸一
        /// </summary>
        public void DoOpenGate1()
        {
            if (pUid != IntPtr.Zero)
            {
                ipcsdk.ICE_IPCSDK_OpenGate(pUid);//开闸 控制IO1输出
            }
        }

        /// <summary>
        /// 打开道闸二
        /// </summary>
        public void DoOpenGate2()
        {
            if (pUid != IntPtr.Zero)
            {
                ipcsdk.ICE_IPCSDK_ControlAlarmOut(pUid, 1);//开闸 控制IO2输出
            }
        }





        #endregion


    }
}
